# main.py
import dearpygui.dearpygui as dpg


from utils.ui import BaseWindow, MenuBar, Sidebar, TrackPanel, PianoRoll




class LinglunStudioMain:
    """
    Minecraft 红石音乐编辑器 DAW 主框架
    支持模块化 UI、音轨管理、插件扩展
    """

    def __init__(self):
        self.project = Project()
        self.plugin_manager = PluginManager()
        self.windows = {}
        self.setup_dearpygui()

    def setup_dearpygui(self):
        """初始化 Dear PyGui"""
        dpg.create_context()
        dpg.create_viewport(width=1200, height=800)
        dpg.show_viewport()
        # dpg.set_primary_window("LingLunStudio", True)

        # 创建主窗口
        self.main_window = BaseWindow("伶伦工作站", width=1200, height=800)
        self.main_window.add_child(MenuBar())
        self.main_window.add_child(Sidebar())
        self.main_window.add_child(TrackPanel(self.project))
        self.main_window.add_child(PianoRoll(self.project))

        # 注册事件
        dpg.set_exit_callback(self.on_close)

    def run(self):
        """运行主循环"""
        dpg.start_dearpygui()

    def on_close(self):
        """关闭时清理"""
        dpg.destroy_context()

    def add_plugin(self, plugin):
        """注册插件"""
        self.plugin_manager.register(plugin)



# core/project.py
class Track:
    """单个音轨对象"""
    def __init__(self, name, instrument="note.harp", volume=0.7, muted=False, soloed=False):
        self.name = name
        self.instrument = instrument
        self.volume = volume
        self.muted = muted
        self.soloed = soloed

    def __repr__(self):
        return f"Track(name='{self.name}', instrument='{self.instrument}')"


class Note:
    """单个音符对象"""
    def __init__(self, pitch, time, duration, velocity=0.7):
        self.pitch = pitch
        self.time = time
        self.duration = duration
        self.velocity = velocity

    def __repr__(self):
        return f"Note(pitch={self.pitch}, time={self.time}, dur={self.duration})"


class Project:
    """项目核心数据模型"""
    def __init__(self):
        self.tracks = [
            Track("这是音轨名称", "note.harp"),
            Track("这是音轨名称", "note.bass"),
            Track("这是音轨名称", "note.piano"),
        ]
        self.notes = [
            Note(60, 0.0, 0.5),  # C4
            Note(64, 0.5, 0.5),  # E4
        ]

    def add_track(self, track):
        self.tracks.append(track)

    def remove_track(self, index):
        if 0 <= index < len(self.tracks):
            del self.tracks[index]


# core/plugin_manager.py
class PluginManager:
    """插件管理器，用于动态加载插件"""
    def __init__(self):
        self.plugins = []

    def register(self, plugin):
        """注册插件"""
        if callable(getattr(plugin, 'on_load', None)):
            plugin.on_load()
        self.plugins.append(plugin)

    def load_from_path(self, path):
        """从路径加载插件（未来实现）"""
        pass


# ===================================
# 主程序入口
# ===================================
if __name__ == "__main__":
    daw = LinglunStudioMain()
    daw.run()